<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="queryParams.userId"
        placeholder="用户编号"
        style="width: 250px"
        class="filter-item"
        @keyup.enter.native="queryBtn"
      />

      <el-input
        v-model="queryParams.parkfieldName"
        placeholder="场站名称"
        style="width: 250px; margin-left: 5px"
        class="filter-item"
        @keyup.enter.native="queryBtn"
      />

      <el-button
        v-waves
        class="filter-item"
        type="primary"
        style="margin-left: 20px"
        icon="el-icon-search"
        @click="queryBtn"
      >
        查询
      </el-button>
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="checkDate"
      >
        导出
      </el-button>
    </div>

    <el-table
      :header-cell-style="{ background: '#ffffff', color: '#000000' }"
      :key="tableKey"
      :row-class-name="tableRowClassName"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="
        width: 100%;
        font-size: 15px;
        box-shadow: 1px 1px 8px #cdcdcd;
        border: 0px;
      "
    >
      <el-table-column
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="订单编号" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{ row.orderId }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户编号" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{ row.userId }}</span>
        </template>
      </el-table-column>

      <el-table-column label="设备名称" min-width="150px">
        <template slot-scope="{ row }">
          <span>{{ row.lockName }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="处理时间" min-width="150px">
        <template slot-scope="{ row }">
          <span></span>
        </template>
      </el-table-column> -->

      <el-table-column
        label="处理"
        width="140"
        fixed="right"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            class="operateBtn"
            size="small"
            type="primary"
            @click="editBtn(scope.$index, scope.row)"
            title="编辑"
            ><i style="font-size:16px;" class="el-icon-edit-outline"></i
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row>
      <el-col :span="24" class="page-tool">
        <el-pagination
          layout="total,sizes,prev, pager,next,jumper"
          style="margin-top: 10px"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 40]"
          @size-change="handlePageChange"
          @current-change="handleNoChange"
        ></el-pagination>
      </el-col>
    </el-row>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form">
        <template>
          <el-row style="margin-bottom: 15px">
            <el-col style="line-height: 36px" :span="2"> 订单编号 </el-col>
            <el-col :span="8">
              <el-input disabled v-model="form.orderId" />
            </el-col>
            <el-col style="line-height: 36px; margin-left: 30px" :span="2">
              用户编号
            </el-col>
            <el-col :span="8">
              <el-input disabled v-model="form.userId" />
            </el-col>
          </el-row>

          <el-row style="margin-bottom: 15px">
            <el-col style="line-height: 50px" :span="2"> 设备名称 </el-col>
            <el-col :span="8">
              <el-input disabled v-model="form.lockName" />
            </el-col>
            <el-col style="line-height: 36px; margin-left: 30px" :span="2">
              场站名称
            </el-col>
            <el-col :span="8">
              <el-input disabled v-model="form.parkfieldName" />
            </el-col>
          </el-row>

          <el-row style="margin-bottom: 15px">
            <el-col style="line-height: 50px" :span="2"> 开始时间 </el-col>
            <el-col :span="8">
              <el-date-picker
                disabled
                v-model="form.startTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 250px; margin-top: 10px"
                type="datetime"
                placeholder="请选择开始时间"
              ></el-date-picker>
            </el-col>
            <el-col style="line-height: 46px; margin-left: 30px" :span="2">
              结束时间
            </el-col>
            <el-col :span="8">
              <el-date-picker
                disabled
                v-model="form.endTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 250px; margin-top: 10px"
                type="datetime"
                placeholder="请选择开始时间"
              ></el-date-picker>
             
            </el-col>
          </el-row>

          <el-row style="margin-bottom: 15px">
            <el-col style="line-height: 36px" :span="2"> 充电费用 </el-col>
            <el-col :span="8">
              <el-input disabled v-model="form.consumeFee" />
            </el-col>
            <el-col style="line-height: 36px; margin-left: 30px" :span="2">
              电量
            </el-col>
            <el-col :span="8">
              <el-input disabled v-model="form.currentNum" />
            </el-col>
          </el-row>

          <el-row style="margin-bottom: 15px">
            <el-col style="line-height: 36px" :span="2"> 占位费 </el-col>
            <el-col :span="8">
              <el-input disabled v-model="form.occupiedFee" />
            </el-col>
            <el-col style="line-height: 36px; margin-left: 30px" :span="2">
              支付方式
            </el-col>
            <el-col :span="8">
              <el-tag
                v-if="form.payWays == '0'"
                size="medium"
                type="success"
                effect="dark"
                style="font-size: 14px"
                >微信</el-tag
              >
              <el-tag
                v-else-if="form.payWays == '1'"
                size="medium"
                type="warning"
                effect="dark"
                style="font-size: 14px"
                >余额</el-tag
              >
              <el-tag
                v-else-if="form.payWays == '2'"
                size="medium"
                type="primary"
                effect="dark"
                style="font-size: 14px"
                >充值</el-tag
              >
              <el-tag
                v-else-if="form.payWays == '3'"
                size="medium"
                type="primary"
                effect="dark"
                style="font-size: 14px"
                >太湖智行</el-tag
              >
              <el-tag
                v-else
                size="medium"
                type="Info"
                style="font-size: 14px"
                >{{ form.lockStatus }}</el-tag
              >
            </el-col>
          </el-row>

          <el-row style="margin-bottom: 15px">
            <el-col style="line-height: 36px" :span="2"> 原因 </el-col>
            <el-col :span="8">
              <el-input v-model="form.reason" />
            </el-col>
          </el-row>

          <el-row style="margin-bottom: 15px">
            <el-col style="line-height: 36px" :span="2"> 说明 </el-col>
            <el-col :span="16">
              <el-input type="textarea" :rows="7" style="height:170px;" v-model="form.state" />
            </el-col>
          </el-row>
        </template>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          处理
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table
        :data="pvData"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false"
          >Confirm</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<style>
.el-table .warning-row {
  background: #fff5ee;
}
.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #fdc091;
}
.el-table__body tr.current-row > td {
  background-color: #fdc091;
}
</style>

<script>
import { listLcChargerLogDetails, exportOrder } from "@/api/order";
import waves from "@/directive/waves"; // waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import axios from "axios";
import { getToken } from "@/utils/auth";
import { loadorderApi, exportChargerLogApi } from "@/api/car";

const calendarTypeOptions = [
  { key: "CN", display_name: "China" },
  { key: "US", display_name: "USA" },
  { key: "JP", display_name: "Japan" },
  { key: "EU", display_name: "Eurozone" },
];

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  name: "ComplexTable",
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger",
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
  },
  data() {
    return {
      //  pickerOptions: {
      //       shortcuts: [{
      //         onClick(picker) {
      //           console.log("1111111111111111");
      //         }
      //          }]
      //     },

      tableKey: 0,
      list: [],
      form: {},
      pageNo: 1,
      queryParams: {
        userId: "",
        name: "",
        startTime: "",
        endTime: "23:59:59",
        lockMac: "",
        parkfieldName: "",
      },
      pageSize: 20,
      multipleSelection: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        name: undefined,
        phone: undefined,
        number: undefined,
        sort: "+id",
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [
        { label: "ID Ascending", key: "+id" },
        { label: "ID Descending", key: "-id" },
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        type: "",
        status: "published",
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "Edit",
        create: "Create",
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [
          { required: true, message: "type is required", trigger: "change" },
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change",
          },
        ],
        title: [
          { required: true, message: "title is required", trigger: "blur" },
        ],
      },
      downloadLoading: false,
    };
  },

  created() {
    //   this.getList()
    this.getStartTime();
    this.getendTime();
  },
  mounted: function () {
    this.$nextTick(function () {
      this.loadorder(this.pageNo, this.pageSize);
    });
    // axios.get("/lcchargerlog/listLcChargerLogDetails?pageNo=1&pageSize=20", {
    //          headers: {
    //           pacargle:getToken()
    //         }}).then((response)=>{
    //           this.loading = true;
    //           console.log(response.data);
    //           this.list = response.data.dataList;
    //           this.total = response.data.totalNum;
    //                     setTimeout(() => {
    //             _this.listLoading = false;
    //           }, 1 * 1000);
    //         })
  },
  methods: {
    editBtn(index, row) {
      let _this = this;
      _this.$nextTick(() => {
        if (_this.$refs.form != undefined) {
          _this.$refs.form.loadorder();
        }
      });
      //   loadFeedbackApi({pageNo:_this.pageNo,pageSize:_this.pageSize}).then(resp => {
      //   _this.list = resp.data.dataList;
      //   _this.total = resp.data.totalNum
      // });
      _this.form = row;
      _this.dialogFormVisible = true;
    },

    change(val) {
      console.log(val);
    },

    getStartTime() {
      let date = new Date();
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      let d = "01";
      let hh = "00";
      let mm = "00";
      let ss = "00";
      let time = y + "-" + m + "-" + d + " " + hh + ":" + mm + ":" + ss;
      this.queryParams.startTime = time;
    },

    getendTime() {
      let date = new Date();
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = "";
      switch (m) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
          d = "31";
          break;
        case 2:
          if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) {
            d = "29";
          } else {
            d = "28";
          }
          break;
        case 4:
        case 6:
        case 9:
        case 11:
          d = "30";
          break;
      }
      let hh = "23";
      let mm = "59";
      let ss = "59";
      let time = y + "-" + m + "-" + d + " " + hh + ":" + mm + ":" + ss;
      this.queryParams.endTime = time;
    },

    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 0) {
        return "warning-row";
      }
      return "";
    },
    sub(value) {
      if (value === null || undefined) {
        return "";
      } else {
        value = value.substring(0, 16);
        return value;
      }
    },
    //列表页码的触发事件
    handlePageChange(pageSize) {
      this.pageSize = pageSize;
      this.loadorder(this.pageNo, this.pageSize);
    },
    handleNoChange(pageNo) {
      this.pageNo = pageNo;
      this.loadorder(this.pageNo, this.pageSize);
    },
    handleTableChange(val) {
      this.multipleSelection = val;
    },
    loadorder(pageNo, pageSize) {
      let _this = this;
      _this.loading = true;
      loadorderApi({
        pageNo: pageNo,
        pageSize: pageSize,
        userId: _this.queryParams.userId,
        name: _this.queryParams.name,
        parkfieldName: _this.queryParams.parkfieldName,
        lockMac: _this.queryParams.lockMac,
        startTime: _this.queryParams.startTime,
        endTime: _this.queryParams.endTime,
      }).then((response) => {
        _this.list = response.data.dataList;
        _this.total = response.data.totalNum;
        setTimeout(() => {
          _this.listLoading = false;
        }, 1 * 1000);
      });
    },

    // queryBtn() {
    //   let _this = this;
    //   _this.loading = true;
    //   this.loadorder(_this.pageNo, _this.pageSize);
    // },

    queryBtn() {
      let _this = this;
      _this.loading = true;
      var stime = new Date(this.queryParams.startTime).getTime();
      var etime = new Date(this.queryParams.endTime).getTime();
      var day = (etime - stime) / (24 * 60 * 60 * 1000);
      if (day <= 0) {
        alert("结束时间不能小于开始时间");
      } else {
        _this.loadorder(_this.pageNo, _this.pageSize);
      }
    },

    //////////////////////////

    // handleFilter() {
    //   this.listQuery.pageNo = 1
    //   this.getList()
    // },
    // handleModifyStatus(row, status) {
    //   this.$message({
    //     message: '操作Success',
    //     type: 'success'
    //   })
    //   row.status = status
    // },
    // sortChange(data) {
    //   const { prop, order } = data
    //   if (prop === 'id') {
    //     this.sortByID(order)
    //   }
    // },
    // sortByID(order) {
    //   if (order === 'ascending') {
    //     this.listQuery.sort = '+id'
    //   } else {
    //     this.listQuery.sort = '-id'
    //   }
    //   this.handleFilter()
    // },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        status: "published",
        type: "",
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          addCar(this.temp).then(() => {
            //     this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Created Successfully",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          updateCar(this.temp).then(() => {
            //     this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Update Successfully",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleDelete(row, index) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteCar({ id: row.id }).then(() => {
          //     this.getList();
          this.dialogFormVisible = false;
          this.$notify({
            title: "Success",
            message: "Delete Successfully",
            type: "success",
            duration: 2000,
          });
        });
      });
    },
    handleFetchPv(pv) {
      fetchPv(pv).then((response) => {
        this.pvData = response.data.pvData;
        this.dialogPvVisible = true;
      });
    },

    checkDate() {
      // var stime = new Date(this.queryParams.startTime.replace(/-/g,'/'));
      // var etime = new Date(this.queryParams.endTime.replace(/-/g,'/'));
      var stime = new Date(this.queryParams.startTime).getTime();
      var etime = new Date(this.queryParams.endTime).getTime();
      var day = (etime - stime) / (24 * 60 * 60 * 1000);
      if (stime == "" || etime == "") {
        alert("请输入开始时间和结束时间");
      } else if (day <= 0) {
        alert("结束时间不能小于开始时间");
      } else if (day > 0 && day <= 730) {
        this.handleDownload();
      } else if (day > 730) {
        alert("开始时间与结束时间差距不得大于2年");
      }

      // this.handleDownload();
    },
    handleDownload() {
      axios({
        method: "GET",
        url: "/lcchargerlog/exportChargerLog",
        params: this.queryParams,
        headers: { pacargle: getToken() },
        responseType: "blob", //返回是个文件
      }).then((response) => {
        this.download(response); //then直接下载，方法在下边
      });
    },
    download(res) {
      let blob = new Blob([res.data], { type: "text/xls,charset=UTF-8" }); //type是文件类，详情可以参阅blob文件类型
      // 创建新的URL并指向File对象或者Blob对象的地址
      const blobURL = window.URL.createObjectURL(blob);
      // 创建a标签，用于跳转至下载链接
      const tempLink = document.createElement("a");
      tempLink.style.display = "none";
      tempLink.href = blobURL;
      tempLink.setAttribute(
        "download",
        decodeURI(
          res.headers["content-disposition"].split(";")[1].split("=")[1]
        )
      );
      // 兼容：某些浏览器不支持HTML5的download属性
      if (typeof tempLink.download === "undefined") {
        tempLink.setAttribute("target", "_blank");
      }
      // 挂载a标签
      document.body.appendChild(tempLink);
      tempLink.click();
      document.body.removeChild(tempLink);
      // 释放blob URL地址
      window.URL.revokeObjectURL(blobURL);
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    },
  },
};
</script>
